const Koa = require('koa');
const app = new Koa();
const json = require('koa-json');
const onerror = require('koa-onerror');
const bodyparser = require('koa-bodyparser');
const cors = require('@koa/cors');
const helmet = require('koa-helmet');
const { koaSwagger } = require('koa2-swagger-ui');
const { loggerMiddleware} = require('./middlewares/logger');
const { catchErrorHandler, responseHandler } = require('./middlewares/response');
const { errorHandler } = require('./middlewares/error');
const { configHandler } = require('./middlewares/config');
const paramValidateHandler = require('./middlewares/validate');
const jwtHandler = require('./middlewares/jwt');
const allRouter = require('./routes');


// error handler
onerror(app);
// middlewares
app.use(loggerMiddleware);
app.use(configHandler);
app.use(errorHandler);
/**
 * helmet 可以帮助你的 app 抵御一些比较常见的安全 web 安全隐患
 * @see {@link https://www.npmjs.com/package/koa-helmet}
 */
// app.use(helmet());
app.use(async (ctx, next) => {
  // 如果请求是针对 Swagger UI 或 Swagger 文档，则跳过 helmet
  if (ctx.path.endsWith('/swagger')) {
    return await next();
  }
  // 使用 koa-helmet
  return helmet()(ctx, next);
});
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}));
app.use(json());
app.use(cors());
app.use(catchErrorHandler);
app.use(jwtHandler);
app.use(paramValidateHandler);
app.use(responseHandler);

// routes

app.use(koaSwagger({
  routePrefix: '/swagger', // 接口文档访问地址
  swaggerOptions: {
    url: '/api/swagger.json', // example path to json 其实就是之后swagger-jsdoc生成的文档地址
  }
}));
app.use(allRouter.routes()).use(allRouter.allowedMethods());
// error-handling
app.on('error', (err, ctx) => {
  ctx.logger.error('server error', err, ctx);
});

module.exports = app;
